import path from 'node:path'
import { defineConfig, loadEnv } from 'vite'
import Components from '@uni-helper/vite-plugin-uni-components'
import Uni from '@dcloudio/vite-plugin-uni'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import ViteCompression from 'vite-plugin-compression'
import ViteRestart from 'vite-plugin-restart'
import { visualizer } from 'rollup-plugin-visualizer'
import { viteVConsole } from 'vite-plugin-vconsole'
console.log('process.platform -> ', process.env.UNI_PLATFORM)
// https://vitejs.dev/config/
export default ({ mode }) => {
  const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
  console.log('打印***env', env)
  const isH5 = process.env.UNI_PLATFORM === 'h5'
  const isProd = mode === 'production'
  const isDev = mode === 'development'

  return defineConfig({
    plugins: [
      Components(),
      Uni({
        vueOptions: {
          template: {
            compilerOptions: {
              // 将所有 ZegoExpress- 开头的标签作为自定义元素处理
              isCustomElement: (tag) => tag.startsWith('ZegoExpress-'),
            },
          },
        },
      }),
      UnoCSS(),
      VueSetupExtend(),
      AutoImport({
        imports: ['vue', 'uni-app'],
        dts: 'src/types/auto-import.d.ts',
        dirs: ['src/hooks'], // 自动导入 hooks
        eslintrc: { enabled: false },
        vueTemplate: true, // default false
      }),
      ViteCompression(),
      ViteRestart({
        restart: ['vite.config.js'],
      }),
      // 打包分析插件
      isProd &&
        visualizer({
          filename: './node_modules/.cache/visualizer/stats.html',
          open: true,
          gzipSize: true,
          brotliSize: true,
        }),
      viteVConsole({
        entry: [path.resolve('src/main.ts')], // 入口文件
        localEnabled: true,
        enabled: isDev && isH5, // 测试环境下开启
        config: {
          // vconsole 配置项
          maxLogNumber: 1000,
          theme: 'light',
        },
      }),
    ],
    resolve: {
      alias: {
        '@': path.join(process.cwd(), './src'),
        '@img': path.join(process.cwd(), './src/static/images'),
      },
    },

    server: {
      host: '0.0.0.0',
      hmr: true,
      port: Number.parseInt(env.VITE_APP_PORT, 10),
      proxy: {
        // 选项写法
        '/api': {
          target: 'http://localhost:6666',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    build: {
      target: 'es2015',
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: isProd,
          drop_debugger: isProd,
        },
      },
      // 解决windows系统对微信小程序自动关闭服务的问题
      watch:
        process.platform === 'win32' // 检测是否为 windows 系统
          ? {
              exclude: ['node_modules/**', '/__uno.css'],
            }
          : null,
    },
  })
}
